package com.gxnu.edu.cn.client.clientConfig;

import com.gxnu.edu.cn.ttxxt.entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.messaging.converter.MappingJackson2MessageConverter;
import org.springframework.messaging.simp.stomp.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import org.springframework.web.socket.messaging.WebSocketStompClient;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

@Component
public class Client {
    private static Client instance;

    @Autowired
    private RestTemplate restTemplate;

    private String baseUrl;
    private String webSocketUrl;

    private ExecutorService executor = Executors.newFixedThreadPool(5);

    private StompSession stompSession;

    public Client() {
        // 私有构造函数
    }

    public static Client getInstance() {
        if (instance == null) {
            synchronized (Client.class) {
                if (instance == null) {
                    instance = new Client();
                }
            }
        }
        return instance;
    }

    public CompletableFuture<Boolean> connect(String serverHost, String serverPort) {
        baseUrl = "http://" + serverHost + ":" + serverPort;
        webSocketUrl = "ws://" + serverHost + ":" + serverPort + "/ws/im";

        return CompletableFuture.supplyAsync(() -> {
            try {
                ResponseEntity<String> response = restTemplate.getForEntity(
                        baseUrl + "/api/test/health",
                        String.class
                );
                return response.getStatusCode().is2xxSuccessful();
            } catch (Exception e) {
                System.err.println("连接异常: " + e.getMessage());
                return false;
            }
        }, executor);
    }

    public void disconnect() {
        executor.shutdown();
    }

    public void connectWebSocket(String username, String ip, StompFrameHandler messageHandler) {
        WebSocketClient client = new StandardWebSocketClient();
        WebSocketStompClient stompClient = new WebSocketStompClient(client);
        stompClient.setMessageConverter(new MappingJackson2MessageConverter());

        stompClient.connect(webSocketUrl, new StompSessionHandlerAdapter() {
            @Override
            public void afterConnected(StompSession session, StompHeaders connectedHeaders) {
                session.subscribe("/topic/messages", messageHandler);
                stompSession = session;
                session.send("/app/chat", "SYSTEM:" + username + ":加入了聊天室");
            }
        });
    }

    public void sendChatMessage(String message) {
        if (stompSession != null) {
            stompSession.send("/app/chat", message);
        }
    }

    public CompletableFuture<Map<String, Object>> login(Map<String, String> credentials, String ip) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                Map<String, String> requestBody = new HashMap<>();
                requestBody.put("username", credentials.get("username"));
                requestBody.put("password", credentials.get("password"));
                requestBody.put("ip", ip); // 添加 IP 地址
                ResponseEntity<Map> response = restTemplate.postForEntity(
                        baseUrl + "/api/users/login",
                        requestBody,
                        Map.class
                );
                return response.getBody();
            } catch (Exception e) {
                throw new RuntimeException("登录失败: " + e.getMessage(), e);
            }
        });
    }
}